package com.cg.asm.core.config.security;

import com.cg.asm.core.domain.vo.user.UserLoginVO;
import com.cg.asm.core.util.AsmApiUtils;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Iterator;

@Component
public class UrlAccessDecisionManager implements AccessDecisionManager {
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, AuthenticationException {
        Iterator<ConfigAttribute> iterator = collection.iterator();
        UserLoginVO userLoginVO = AsmApiUtils.getCurrentUserLoginVO();
        if (null != userLoginVO) {
            while (iterator.hasNext()) {
                ConfigAttribute ca = iterator.next();
                //当前请求需要的权限
                String needRole = ca.getAttribute();
                if("ROLE_REQUEST_PASSED".equals(needRole)){
                    return;
                }
                if("ROLE_REQUEST_DENIED".equals(needRole)){
                    throw new AccessDeniedException("权限不足!");
                }
                //当前请求没有匹配上角色，则为登录访问
                if ("ROLE_LOGIN".equals(needRole)) {
                    throw new BadCredentialsException("未登录");
                } else {
                    return;
                }
            }
        }
        throw new AccessDeniedException("非法访问!");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}